﻿using Kevin.Comm.Utility.Crypto;
using Kevin.Shop.Business.Core.Components.Cookie;
using Kevin.Shop.Business.Service.Entity.Helper;
using Kevin.Shop.Business.Service.Entity.StoreManagement.Enumerations;
using RiderShop.Mobile.Common.Component;
using RiderShop.Mobile.Common.Helper;
using RiderShop.Mobile.Modle;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace RiderShop.Mobile.Controllers
{

    public partial class CustomerController : ThemeController
    {

        string verifyCodeKey = "VerifyCode";
        public ActionResult VerifyCodeImage()
        {
            string url = ConfigurationManager.AppSettings["DefaultHost"].Trim() + "/VerifyCodeImage.ashx?ref=1&t=" + DateTime.Now.ToString("hhmmss");
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            request.CookieContainer = new CookieContainer();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string verifyCode = response.Cookies[verifyCodeKey].Value.ToLower();
            KevinCookieManager.Set(FindPasswordModel.VerifyCodeKey, SystemEncrypt.Encrypt(verifyCode));


            return File(response.GetResponseStream(), response.ContentType);
        }


        public ActionResult GetPass()
        {
            FindPasswordModel model = new FindPasswordModel();
            return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            //return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", "_MobileLayout", model);
        }

        [HttpPost]
        public ActionResult GetPass(FindPasswordModel model)
        {
            if (string.IsNullOrEmpty(model.VerifyCode) || !FindPasswordModel.CheckVerifyCode(model.VerifyCode))
            {
                model.Message = "验证码不正确";
                return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
                //return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", "_MobileLayout", model);
            }

            if (string.IsNullOrEmpty(model.UserName))
            {
                model.Message = "用户不存在";
                return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
                //return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", "_MobileLayout", model);
            }

            var userInfo = CacheUsers.Get(model.UserName, true);

            if (userInfo != null && userInfo.UserId > 0)
            {
                return RedirectToAction("GetPassWay", "Customer", new { userName = userInfo.UserName, tk = SystemEncrypt.Encrypt(userInfo.UserName) });
            }
            else
            {
                model.Message = "用户不存在";
            }
            return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            //return View(WebClientContext.Current.SiteTheme, "Customer", "GetPass", "_MobileLayout", model);
        }

        public ActionResult GetPassWay(string userName, string tk)
        {
            if (string.IsNullOrEmpty(userName) || SystemEncrypt.Encrypt(userName) != tk)
            {
                return RedirectToAction("GetPass", "Customer");
            }

            var userInfo = CacheUsers.Get(userName, true);
            FindPasswordModel model = new FindPasswordModel();
            model.UserInfo = userInfo;

            return View(WebClientContext.Current.SiteTheme, "Customer", "GetPassWay", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            //return View(WebClientContext.Current.SiteTheme, "Customer", "GetPassWay", "_MobileLayout", model);
        }

        public ActionResult FindPasswordByEmail(string userName, string tk)
        {
            if (string.IsNullOrEmpty(userName) || SystemEncrypt.Encrypt(userName) != tk)
            {
                return RedirectToAction("GetPass", "Customer");
            }

            var userInfo = CacheUsers.Get(userName, true);
            FindPasswordModel model = new FindPasswordModel();
            model.UserInfo = userInfo;
            model.FindPasswordByEmail(userInfo.UserName, userInfo.Email);
            return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByEmail", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            //return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByEmail", "_MobileLayout", model);
        }
        public ActionResult FindPasswordByPhone(string userName, string tk, int action = 0)
        {
            if (!WebClientContext.Current.IsAuthenticated)
            {
                if (string.IsNullOrEmpty(userName) || SystemEncrypt.Encrypt(userName) != tk)
                {
                    return RedirectToAction("GetPass", "Customer");
                }
            }
            else
            {
                userName = WebClientContext.Current.UserName;
            }
            var userInfo = CacheUsers.Get(userName, true);
            FindPasswordModel model = new FindPasswordModel();
            model.UserInfo = userInfo;
            model.ActionType = (FindPasswordAction)action;
            return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            //return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", "_MobileLayout", model);
        }

        [HttpPost]
        public ActionResult SendSMSValdateCode(string userName, string cellPhone, int type = 3)
        {
            //string userName = "", cellPhone = "";
            if (string.IsNullOrWhiteSpace(cellPhone))
            {
                return Json("您输入的手机号不正确！");
            }

            if (!(new System.Text.RegularExpressions.Regex("^1\\d{10}$")).IsMatch(cellPhone))
            {
                return Json("请输入正确手机号");
            }
            int userId = 0;
            if (!string.IsNullOrEmpty(userName) || (SMSSendType)type != SMSSendType.Register)
            {
                var userInfo = CacheUsers.Get(userName, true);
                if (userInfo == null)
                {
                    return Json("您输入的手机号不正确！");
                }

                //没有登录为找回密码模式，已登录则绑定手机号并可重置密码
                if (!WebClientContext.Current.IsAuthenticated)
                {
                    if (userInfo.CellPhone != cellPhone.Trim())
                    {
                        return Json("您输入的手机号不正确！");
                    }
                }

                userId = userInfo.UserId;
            }

            if ((SMSSendType)type == SMSSendType.Register)
            {
                var newUser = CacheUsers.Get(cellPhone, true);
                if (newUser != null && newUser.UserId > 0)
                {
                    return Json("该手机号已注册！");
                }
            }

            var response = FindPasswordModel.SendSMSAuthentiCode(userId, cellPhone, (SMSSendType)type);
            if (!response.Status)
            {
                return Json(response.ErrorMessage);
            }


            return Json("");
        }

        [HttpPost]
        public ActionResult FindPasswordByPhone(FindPasswordModel model)
        {
            if (string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.CellPhone))
            {
                model.Message = "您输入的手机号不正确！";
                return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }

            var userInfo = CacheUsers.Get(model.UserName, false);
            model.UserInfo = userInfo;

            if (userInfo.CellPhone != model.CellPhone.Trim())
            {
                model.Message = "您输入的手机号不正确！";
                return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }

            var response = FindPasswordModel.VefifySMSAuthentiCode(userInfo.UserId, model.VerifyCode, SMSSendType.ChangePassword);
            if (!response.Status)
            {
                model.Message = response.ErrorMessage;
                return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }

            response = model.FindPasswordByEmail(userInfo.UserName, userInfo.CellPhone);
            if (response.Status)
            {
                return RedirectToAction("ResetPassword", "Customer", new { forgetpwd = response.Tag, action = (int)model.ActionType });
            }
            else
            {
                model.Message = "服务异常，请重试！";
                return View(WebClientContext.Current.SiteTheme, "Customer", "FindPasswordByPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }
        }


        public ActionResult ResetPassword(string forgetpwd)
        {

            if (string.IsNullOrEmpty(forgetpwd))
            {
                return RedirectToAction("GetPass", "Customer");
            }

            var customer = new CustomerModel();

            return View(WebClientContext.Current.SiteTheme, "Customer", "ResetPassword", WebClientContext.Current.CacheKeyDefaultMasterPage, customer);
        }

        [HttpPost]
        public ActionResult ResetPassword(string newPwd, string forgetpwd)
        {
            if (string.IsNullOrEmpty(forgetpwd))
            {
                return Json("验证码过期，请重试！");
            }

            var customer = new CustomerModel();

            if (string.IsNullOrEmpty(newPwd) || newPwd.Length < 6 || newPwd.Length > 30)
            {
                return Json("密码长度为6到30！");
            }

            customer.ResetPassword(newPwd, forgetpwd);

            if (WebClientContext.Current.IsAuthenticated)
            {
                var userInfo = WebClientContext.Current.GetCurrentUser();
                if (userInfo.MSN == "weixinfirstlogin")
                {
                    userInfo.MSN = "";//清楚微信注册标记字段
                    RiderShop.Mobile.Modle.MyAccount.MyAccountModel.UpdateUser(userInfo);
                }
            }

            if (customer.Result != null && !customer.Result.Status)
            {
                return Json(customer.Result.ErrorMessage);
            }

            return Json("");

        }

        [Authorize]
        public ActionResult BindCellPhone()
        {
            FindPasswordModel model = new FindPasswordModel();
            model.UserInfo = WebClientContext.Current.CurrentUser;
            if (model.UserInfo.IsCellPhoneVerified)
            {
                model.ActionType = FindPasswordAction.UnBindingCellPhone;
            }
            else
            {
                model.ActionType = FindPasswordAction.BindingCellPhone;
            }
            model.CellPhone = WebClientContext.Current.CurrentUser.CellPhone;
            return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
        }

        [Authorize]
        [HttpPost]
        public ActionResult BindCellPhone(FindPasswordModel model)
        {
            var userInfo = WebClientContext.Current.GetCurrentUser(false);
            model.UserInfo = userInfo;

            if (string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.CellPhone))
            {
                model.Message = "您输入的手机号不正确！";
                return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }

            if (string.IsNullOrEmpty(model.VerifyCode))
            {
                model.Message = "验证码不正确！";
                return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
            }

            if (model.ActionType == FindPasswordAction.BindingCellPhone || model.ActionType == FindPasswordAction.ReBindingCellPhone)
            {
                if (userInfo.IsCellPhoneVerified && model.ActionType != FindPasswordAction.ReBindingCellPhone)
                {
                    model.Message = "已绑定手机号!";
                    return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
                }

                var response = FindPasswordModel.UpdateUserVerifiedCellPhone(userInfo.UserId, model.CellPhone, model.VerifyCode);
                if (!response.Status)
                {
                    model.Message = response.ErrorMessage;
                    return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
                }
                WebClientContext.Current.GetCurrentUser(false);
                return RedirectToAction("Profile", "MyAccount");
            }
            else if (model.ActionType == FindPasswordAction.UnBindingCellPhone)
            {
                if (userInfo.CellPhone.Trim() != model.CellPhone.Trim())
                {
                    model.Message = "您输入的手机号不正确！";
                    return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
                }

                var response = FindPasswordModel.VefifySMSAuthentiCode(userInfo.UserId, model.VerifyCode, SMSSendType.BindCellPhone);
                if (!response.Status)
                {
                    model.Message = response.ErrorMessage;
                    return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);
                }

                model.ActionType = FindPasswordAction.ReBindingCellPhone;
                return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);

            }

            return View(WebClientContext.Current.SiteTheme, "Customer", "BindCellPhone", WebClientContext.Current.CacheKeyDefaultMasterPage, model);

        }

    }


}
